using System.Xml.Linq;
using IDeal.Extensions;
using IDeal.Models;
using IDeal.Services;

namespace IDeal.Serialization
{
    internal abstract class XmlMessageWriter<T> : IXmlMessageWriter<T> where T:XmlRequest
    {
        public IIDealServices IDealServices { get; set; }
        protected abstract string RootElementName { get; }
        protected readonly XNamespace Ns = XNamespace.Get("http://www.idealdesk.com/Message");

        protected XmlMessageWriter(IIDealServices iDealServices)
        {
            IDealServices = iDealServices;
        }

        public string ToXml(T value)
        {
            var rootElement = new XElement(
                Ns + RootElementName, new XAttribute("version", "1.1.0"),
                new XElement(Ns + "createDateTimeStamp", value.CreatedDateTimeStamp.ToIDealFormat())
                );

            SetupRootElement(value, rootElement);

            var document = new XDocument(
                new XDeclaration("1.0", "UTF-8", "yes"),
                rootElement
                );

            return document.Declaration + rootElement.ToString();
        }

        protected abstract void SetupRootElement(T element, XElement rootElement);
        protected abstract string GetHashSource(T instance);

        protected Signature CreateSignature(T instance)
        {
            return IDealServices.CryptoServices.CreateSignature(GetHashSource(instance));
        }
    }
}